<template>
  <div class="account-box">
    <!-- 切换账号和短信登录 -->
    <div class="toggle">
      <a @click="isMsgLogin = false" href="javascript:;" v-if="isMsgLogin">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a @click="isMsgLogin = true" href="javascript:;" v-else>
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <!-- 账号登录表单和短信登录表单 -->
    <!--schema是定义的验证规则; v-slot是作用域插槽，把验证组件中的错误信息传递到errors对象 -->
    <Form ref="loginForm" autocomplete="off" class="form" :validation-schema="schema" v-slot="{ errors }">
      <!-- 账号登录 -->
      <template v-if="!isMsgLogin">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field :class="{ error: errors.account }" type="text" name="account" v-model="form.account"
              placeholder="请输入用户名" />
          </div>
          <!-- 错误的提示信息 -->
          <div v-if="errors.account" class="error"><i class="iconfont icon-warning" />{{ errors.account }}</div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <Field :class="{ error: errors.password }" type="password" name="password" v-model="form.password"
              placeholder="请输入密码" />
          </div>
          <!-- 错误的提示信息 -->
          <div v-if="errors.password" class="error"><i class="iconfont icon-warning" />{{ errors.password }}</div>
        </div>
      </template>
      <!-- 短信登录 -->
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field :class="{ error: errors.mobile }" type="text" name="mobile" v-model="form.mobile"
              placeholder="请输入手机号" />
          </div>
          <div v-if="errors.mobile" class="error"><i class="iconfont icon-warning" />{{ errors.mobile }}</div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <Field :class="{ error: errors.code }" type="text" name="code" v-model="form.code" placeholder="请输入验证码" />
            <span :class="{ disabled: time }" @click="send" class="code"> {{ time === 0 ? '发送验证码' : `${time}秒后发送`
            }}</span>
          </div>
          <div v-if="errors.code" class="error"><i class="iconfont icon-warning" />{{ errors.code }}</div>
        </div>
      </template>
      <!-- 共同的协议和按钮 -->
      <div class="form-item">
        <div class="agree">
          <!-- 一定要确保该组件做了双向数据绑定 -->
          <Field as="XtxCheckbox" name="isAgree" v-model="form.isAgree" />
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div v-if="errors.isAgree" class="error"><i class="iconfont icon-warning" />{{ errors.isAgree }}</div>
      </div>
      <a @click="login" href="javascript:;" class="btn">登录</a>
    </Form>
    <!-- QQ登录的预留区 -->
    <div class="action">
      <!-- 跳到授权登录的页面 -->
      <a
        href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
        <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="">
      </a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>
<script>
import { ref, reactive, watch, onUnmounted } from 'vue'
import { Form, Field } from 'vee-validate'
// 导入外部定义的验证规则
import commonValidate from '@/hooks/vee-validate-schema'
import { userAccountLogin, userMobileLoginMsg, userMobileLogin } from '@/api/user'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import Message from '@/components/library/Message'
import { useIntervalFn } from '@vueuse/core'
// import QC from 'qc'
export default {
  name: 'LoginForm',
  /* created() {
    this.$message({ type: 'success', text: '登录成功' })
  }, */
  components: {
    Form, Field
  },
  setup() {
    const store = useStore()
    const route = useRoute()
    const router = useRouter()
    // QQ登录测试，生成一个QQ头像，并带有跳转到登录页面的功能
    /* onMounted(() => {
      QC.Login({
        btnId: 'qqLoginBtn'
      })
    }) */
    // 是否短信登录
    const isMsgLogin = ref(false)
    // 收集表单数据
    const form = reactive({
      account: 'lau1234567',
      password: '123456',
      code: '',
      mobile: '',
      isAgree: true
    })
    // 指定表单的校验规则
    const schema = {
      account: commonValidate.account,
      password: commonValidate.password,
      mobile: commonValidate.mobile,
      code: commonValidate.code,
      isAgree: commonValidate.isAgree
    }
    // 获取表单的dom对象
    const loginForm = ref(null)
    // 切换表单元素，还原数据和清除校验效果
    watch(isMsgLogin, () => {
      // 还原数据
      form.isAgree = true
      form.account = null
      form.password = null
      form.mobile = null
      form.code = null
      // 补充校验效果清除，Form组件提供resetForm()
      loginForm.value.resetForm()
    })
    // 得到组件的实例，相当于this
    // const { proxy } = getCurrentInstance()
    // proxy.$message({ type: 'success', text: 'ok' })
    // 登录
    const login = async () => {
      // 表单校验：结果为true和false
      const valid = await loginForm.value.validate()
      if (valid) {
        try {
          // 账号和密码登录
          if (!isMsgLogin.value) {
            // 发送网络请求，进行登录
            const { result: { id, account, avatar, mobile, token } } = await userAccountLogin({ account: form.account, password: form.password })
            // 更新vuex的中用户模块的数据
            store.commit('user/setUser', { id, account, avatar, mobile, token })
          } else {
            // 短信登录
            // 1. 定义两个API  短信登录，获取短信验证码
            // 2. 实现发送短信验证码发送功能
            // 3. 完成手机号短信验证码登录逻辑
            const { result: { id, account, avatar, mobile, token } } = await userMobileLogin({ mobile: form.mobile, code: form.code })
            // 更新vuex的中用户模块的数据
            store.commit('user/setUser', { id, account, avatar, mobile, token })
          }
          // 登录成功后合并本地购物车数据到服务器并且清空本地购物车数据
          store.dispatch('cart/mergeLocalCart').then(() => {
            Message({ type: 'success', text: '登录成功' })
            // 跳转到发起登录前的地址中
            router.push(decodeURIComponent(route.query.redirectUrl || store.state.user.redirectUrl))
        })
      } catch (err) {
        Message({ type: 'error', text: err.response.data.message })
      }
    }
  }
    // 发送短信验证码
    // pause 暂停 resume 开始
    // 开启定时器：useIntervalFn(回调函数,执行间隔,是否立即开启)
    const time = ref(0)
    const { pause, resume } = useIntervalFn(() => {
    // 开启了定时器要实现业务
    time.value--
    if (time.value <= 0) {
      pause() // 停止定时器
    }
  }, 1000, false)
    // 组件销毁时清除定时器
    onUnmounted(() => {
  pause()
})
const send = async () => {
  // 需要对用户填写的手机号码做校验
  //  由于点击发送验证码的行为，并不需要手机号码选项失去焦点或者是提交表单时触发，主动触发表单的验证规则
  const valid = schema.mobile(form.mobile)
  if (valid === true) {
    if (time.value === 0) {
      // 没有倒计时才可以发送
      try {
        await userMobileLoginMsg(form.mobile)
        Message({ type: 'success', text: '发送成功' })
        // 时间设置为60秒倒计时
        time.value = 60
        resume() // 开启定时器
      } catch (err) {
        Message({ type: 'error', text: err.response.data.message })
      }
    }
  } else {
    // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
    loginForm.value.setFieldError('mobile', valid)
  }
}
return { isMsgLogin, form, schema, login, loginForm, send, time }
  }
}
</script>
<style lang="less" scoped>
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;

    a {
      color: @xtxColor;

      i {
        font-size: 14px;
      }
    }
  }

  .form {
    padding: 0 40px;

    &-item {
      margin-bottom: 28px;

      .input {
        position: relative;
        height: 36px;

        >i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }

        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;

          &.error {
            border-color: @priceColor;
          }

          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }

        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;

          &.active {
            pointer-events: auto;
          }

          &.disabled {
            pointer-events: none;
          }
        }
      }

      >.error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;

        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }

    .agree {
      a {
        color: #069;
      }
    }

    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;

      &.disabled {
        background: #cfcdcd;
      }
    }
  }

  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>